//
//  BusWebService.m
//  Bus_iPhone
//
//  Created by 修勇 黄 on 12-7-19.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "BusWebService.h"
#import "Reachability.h"
#import "SBJson.h"

@implementation BusWebService

@synthesize delegate=_delegate;


-(id)init{

    self=[super init];
    if (self) {
        busDownFileQueue=[[ASINetworkQueue alloc]init];
        [busDownFileQueue go];
        [busDownFileQueue setShouldCancelAllRequestsOnFailure:NO];
        [busDownFileQueue setMaxConcurrentOperationCount:2];
        [busDownFileQueue setDelegate:self];
        [busDownFileQueue setQueueDidFinishSelector:@selector(downLoadFinish)];
    }
    return self;
}

-(NSInteger)checkNetWork{

    Reachability* wifi = [Reachability reachabilityForLocalWiFi];
    [wifi startNotifier];
    NetworkStatus netStatus = [wifi currentReachabilityStatus];
    if (netStatus==NotReachable) {
        Reachability *internet=[Reachability reachabilityForInternetConnection];
        [internet startNotifier];
        netStatus=[internet currentReachabilityStatus];
        if (netStatus==NotReachable) {
            return 0;
        }else {
            return 2;
        }
    }else {
        return 1;
    }
    return 0;
}

-(ASIHTTPRequest *)postRequestWithDic:(NSDictionary *)dic{

    if ([self checkNetWork]==0) {
        return nil;
    }
   // NSLog(@"dic %@",dic);
    NSString *json=[dic JSONRepresentation];
    ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:[NSURL URLWithString:kRequesetURL]];
    [request setRequestMethod:@"POST"];
    [request setStringEncoding:NSUTF8StringEncoding];
    [request setPostValue:json forKey:@"Post"];
    request.timeOutSeconds=15;
    return request;
}



-(BOOL)addDwonLoadFileWithHost:(NSString *)host fileName:(NSString *)fileName progress:(id)progress{

    NSURL *url=[NSURL URLWithString:host];
    if (!url) {
        return NO;
    }
    ASIHTTPRequest *request=[ASIHTTPRequest requestWithURL:url];
    request.timeOutSeconds=15;
    request.userInfo=[NSDictionary dictionaryWithObjectsAndKeys:@"down",@"type",fileName,@"name", nil];
    NSString *tempfolderPath = [NSHomeDirectory() stringByAppendingPathComponent:@"tmp"];
    NSFileManager *fileManger = [NSFileManager defaultManager];
    if (![fileManger fileExistsAtPath:tempfolderPath]) {
        [fileManger createDirectoryAtPath:tempfolderPath withIntermediateDirectories:NO attributes:nil error:nil];
    }
    tempfolderPath=[tempfolderPath stringByAppendingPathComponent:fileName];
  //  NSLog(@"down %@",host);
    [request setTemporaryFileDownloadPath:tempfolderPath];
    [request setAllowResumeForFileDownloads:YES];
    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDir = [documentPaths objectAtIndex:0];
    NSString *filePath=[documentDir stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.db",fileName]];
   // NSLog(@"file path %@",filePath);
    [request setDownloadDestinationPath:filePath];
    request.downloadProgressDelegate=progress;
    request.delegate=self;
    [busDownFileQueue addOperation:request];
    
    return YES;
}

-(BOOL)cancelDownLoadFileByHost:(NSString *)host{

    NSURL *url=[NSURL URLWithString:host];
    if (!url) {
        return NO;
    }
    
    BOOL isFound=NO;
    for (ASIHTTPRequest *request in busDownFileQueue.operations) {
        if ([request.url isEqual:url]) {
            [request clearDelegatesAndCancel];
            isFound=YES;
        }
    }
    return isFound;
}

-(void)clearAllProgress{

    for (ASIHTTPRequest *request in busDownFileQueue.operations) {
        [request setDownloadProgressDelegate:nil];
    }
}
-(BOOL)addProgressDelegate:(id)progress name:(NSString *)name{

    for (ASIHTTPRequest *request in busDownFileQueue.operations) {
        if ([[request.userInfo objectForKey:@"name"] isEqualToString:name]) {
            [request setDownloadProgressDelegate:progress];
            return YES;
        }
    }
    return NO;
}
-(BOOL)addProgressDelegate:(id)progress host:(NSString *)host{

    
    NSURL *url=[NSURL URLWithString:host];
    if (!url) {
        return NO;
    }
    
    for (ASIHTTPRequest *request in busDownFileQueue.operations) {
        if ([request.url isEqual:url]) {
            [request setDownloadProgressDelegate:progress];
            return YES;
        }
    }
    return NO;
}

-(BOOL)checkIsHadDownByHost:(NSString *)host{

    NSURL *url=[NSURL URLWithString:host];
    if (!url) {
        return NO;
    }
    
    for (ASIHTTPRequest *request in busDownFileQueue.operations) {
        if ([request.url isEqual:url]&&request.isCancelled==NO) {
            return YES;
        }
    }
    return NO;
    
}

-(BOOL)checkIShadDownByName:(NSString *)name{

    for (ASIHTTPRequest *request in busDownFileQueue.operations) {
        
        if ([[request.userInfo objectForKey:@"name"] isEqualToString:name]&&request.isCancelled==NO) {
            return YES;
        }
    }
    return NO;
}
#pragma mark -ASIHTTPRequestDelegate

-(void)request:(ASIHTTPRequest *)request didReceiveResponseHeaders:(NSDictionary *)responseHeaders{

    if ([[responseHeaders objectForKey:@"Content-Type"] isEqualToString:@"text/html"]) {
        [request cancel];
    }
}

-(void)requestFailed:(ASIHTTPRequest *)request{

    if (request.isCancelled) {
        NSLog(@"YES");
    }else
        NSLog(@"NO");
//    NSLog(@"string %@",request.responseString);
    if ([[request.userInfo objectForKey:@"type"] isEqualToString:@"down"]) {
        if (_delegate&&[_delegate respondsToSelector:@selector(busFileDownFailed:error:)]) {
            [_delegate busFileDownFailed:request error:request.error];
        }
    }
}

-(void)requestFinished:(ASIHTTPRequest *)request{

    if (request.isCancelled) {
        NSLog(@"YES");
    }else
        NSLog(@"NO");
//    NSLog(@"string %@",request.responseString);
    
    if ([[request.userInfo objectForKey:@"type"] isEqualToString:@"down"]) {
        if (_delegate&&[_delegate respondsToSelector:@selector(busFileDownSuccess:)]) {
            [_delegate busFileDownSuccess:request];
        }
    }
}

-(void)downLoadFinish{

    if (_delegate&&[_delegate respondsToSelector:@selector(busFileAllDownLoad)]) {
        [_delegate busFileAllDownLoad];
    }
}
@end
